package systemController

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"wisdomCoach/global"
	"wisdomCoach/model"

	"github.com/gin-gonic/gin"
)

func GetDictDataType(c *gin.Context) {
	var dictDataList []model.DictData
	dictType := c.Param("dictType")

	ctx := context.Background()
	key := "sys_dict:" + dictType
	redisData, _ := global.REDIS.Get(ctx, key).Result()
	if redisData != "" {
		if err := json.Unmarshal([]byte(redisData), &dictDataList); err != nil {
			fmt.Println("json数据格式转换失败")
		} else {
			c.JSON(http.StatusOK, gin.H{
				"code":    200,
				"data":    dictDataList,
				"message": "操作成功",
			})
			return
		}
	}

	if err := global.DB.Where("dict_type = ?", dictType).Find(&dictDataList).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "字典查询不到，服务器异常",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"data":    dictDataList,
		"message": "操作成功",
	})
	dictDataJson, _ := json.Marshal(dictDataList)
	global.REDIS.Set(ctx, key, dictDataJson, 0).Result()
}
